package com.artron.mediaartron.data.task;

import android.util.Log;

import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.data.entity.UploadIcon;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.util.IOUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okio.BufferedSink;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.content.ContentValues.TAG;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-11-02.
 */

public class UserIconUploadTask {

    public static void uploadUserIcon(String token, final String path,
                               final Action1<Response<UploadIcon>> callback) {

        int pointIndex = path.indexOf(".");
        int separator = path.lastIndexOf("/");
        String fileName = path.substring(separator + 1);
        final String type = path.substring(pointIndex + 1);

        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                if ("jpg".equals(type) || "jpeg".equals(type)) {
                    return MediaType.parse("image/jpeg");
                }

                return MediaType.parse("image/png");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                BufferedInputStream bufIs = new BufferedInputStream(new FileInputStream(path));
                try {
                    byte[] buf = new byte[1024 * 1024];
                    int len;
                    while ((len = bufIs.read(buf)) != -1) {
                        sink.write(buf, 0, len);
                    }
                    sink.flush();
                } catch (IOException e) {
                    Log.e(TAG, "writeTo: ", e);
                } finally {
                    IOUtils.close(bufIs);
                }
            }
        };

        MultipartBody.Part part = MultipartBody.Part.createFormData("file", fileName, body);
        RetrofitHelper.getLoginApi().modifyUserPhoto(token, part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Response<UploadIcon>>() {
                    @Override
                    public void call(Response<UploadIcon> response) {
                        callback.call(response);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        MobclickAgent.reportError(UIUtils.getContext(), throwable);
                    }
                });
    }
}
